3
3
.
.
1
1
.
.
5
5
@
@
P
P
u
u
b
b
l
l
i
i
s
s
h
h
e
e
d
d
I
I
n
n
f
f
o
o
[
[
R
R
]
]
[
[
R
R
]
]
[
[
R
R
]
]
This tutorial shows a simple example on how to use: ObservableObject, @Published, @ObservedObject.
When Property marked as @Published is changed, body Property of any View that uses that Property will be redrawn.
So it has the same purpose as @State for struct.
@Published can be used only inside a Class that implements ObservableObject Protocol.
Instance of such Class must be flagged with @ObservedObject.
This tells SwiftUI that you actually want to observe this Object in order to use this feature.
E
E
x
x
a
a
m
m
p
p
l
l
e
e
As soon as the View is loaded Property name is changed to "Bill" and the View is redrawn with this new value.
ContentView.swift
import SwiftUI
class Person : ObservableObject {
@Published var name = "John"
}
struct ContentView: View {
@ObservedObject var person = Person()
var body: some View {
VStack {
Button("Button") { self.person.name = "Bill" } //Change name Propert in Class Instance
Text(person.name) //Change to name is detected and View is redrawn
TextField("Enter Name", text: $person.name) //Reference to person.
}
}
}